package com.hcrazy.manchester.app.controllers;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.DiskFileUpload;
import org.apache.commons.fileupload.FileItem;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.hcrazy.manchester.app.pojo.ErrorMsg;
import com.hcrazy.manchester.app.pojo.XeditorErrorMsg;
import com.hcrazy.manchester.app.utils.Constant;
import com.hcrazy.manchester.app.utils.Log;

@Controller
public class FileUploadController {

	/**
	 * 添加图片
	 * 
	 * @param file
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/api/func/image", method = RequestMethod.POST)
	public @ResponseBody
	Object uploadImage(
			@RequestParam("file") CommonsMultipartFile file,
			HttpServletRequest req,
			@RequestParam(required = false) Integer width,
			@RequestParam(required = false) Integer height) {
		
		if(null == width) width = 0;
		if(null == height) height = 0;

		String success = fileUpload(file, req,width,height);
		if (null != success) {
			Map<String, String> result = new HashMap<String, String>();
			result.put(Constant.SINGLE_RETURN, success);
			result.put("SIZE", width+":"+height);
			return result;
		} else {
			return new ErrorMsg(Constant.UPLOAD_IMAGE_FAILED, "上传失败！");
		}

	}
	
	/**
	 * 添加图片
	 * 
	 * @param file
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/api/image", method = RequestMethod.POST)
	public @ResponseBody
	Object uploadCommonImage(@RequestParam("file") CommonsMultipartFile file,
			HttpServletRequest req) {

		String success = fileUpload(file, req,null,null);
		if (null != success) {
			Map<String, String> result = new HashMap<String, String>();
			result.put(Constant.SINGLE_RETURN, success);
			return result;
		} else {
			return new ErrorMsg(Constant.UPLOAD_IMAGE_FAILED, "上传失败！");
		}

	}

	@RequestMapping(value = "/fileupload", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
	public @ResponseBody
	String fileUpload(
			@RequestParam("file") CommonsMultipartFile file,
			HttpServletRequest request,
			@RequestParam(required = false) Integer width,
			@RequestParam(required = false) Integer height) {

		if (!file.isEmpty()) {
			
			String path = request.getSession().getServletContext()
					.getRealPath("/resources/fileupload/");
			String suffix = file.getOriginalFilename().substring(
					file.getOriginalFilename().lastIndexOf("."));
			String name = UUID.randomUUID().toString();
			
			if(null != width && width > 0){
				name = name + "_" + width;
			}
			if(null != height && height > 0){
				name = name + "__" + height;
			}
			
			String filePath = path + File.separator + name + suffix;

			File saveFile = new File(filePath);

			try {
				file.getFileItem().write(saveFile);

				return name + suffix;
			} catch (Exception e) {
				Log.error(e.getMessage(), e);
				return null;
			}

		}

		return null;

	}
	
	/*@RequestMapping(value = "/upload", method = RequestMethod.POST)  
    public @ResponseBody String upload(HttpServletRequest request) throws IOException {  
		String path = request.getSession().getServletContext().getRealPath("/resources/fileupload");
        if ("application/octet-stream".equals(request.getContentType())) {  
            try {  
                String dispoString = request.getHeader("Content-Disposition");  
                int iFindStart = dispoString.indexOf("filename =\"") + 10;  
                int iFindEnd = dispoString.indexOf("\"", iFindStart);  
                String sFileName = dispoString.substring(iFindStart, iFindEnd);  
                int i = request.getContentLength();  
                byte buffer[] = new byte[i];  
                int j = 0;  
                while (j < i) { //获取表单的上传文件  
                    int k = request.getInputStream().read(buffer, j, i - j);  
                    j += k;  
                }  
                if (buffer.length >= 0) { //文件是否为空  
                	
                    String uploadFile = UploadUtils.generateFilename(path, UploadUtils.getExtension(sFileName, "jpg"));  
                    File file = new File(uploadFile);  
                    OutputStream out = new BufferedOutputStream(new FileOutputStream(file, true));  
                    out.write(buffer);  
                    out.close();  
                    m.addAttribute("url", uploadFile.replace(path, "/upload"));  
                    m.addAttribute("local", uploadFile);  
                }  
            } catch (Exception ex) {  
                m.addAttribute("err", ex.getMessage());  
            }  
        }  
        return "upload";  
    }  */
	
	@RequestMapping(value = "/xheditor/fileupload", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
	public @ResponseBody XeditorErrorMsg fileUpload_(
			@RequestParam("filedata") CommonsMultipartFile file,
			HttpServletRequest request) {

		if (!file.isEmpty()) {

			String path = request.getSession().getServletContext()
					.getRealPath("/resources/fileupload/");
			String suffix = file.getOriginalFilename().substring(
					file.getOriginalFilename().lastIndexOf("."));
			String name = UUID.randomUUID().toString();
			String filePath = path + File.separator + name + suffix;

			File saveFile = new File(filePath);

			try {
				file.getFileItem().write(saveFile);
				String finalname = Constant.DOMAIN + request.getContextPath()+"/resources/fileupload/"+name + suffix;
				return new XeditorErrorMsg("",finalname);
			} catch (Exception e) {
				Log.error(e.getMessage(), e);
				return new XeditorErrorMsg(e.getMessage(),"");
			}

		}

		return null;

	}

	/**
	 * 上传用户头像
	 * 
	 * @param userInfo
	 * @param map
	 * @param req
	 * @return
	 */
	@RequestMapping(value = "/api/user/header111", method = RequestMethod.POST)
	public @ResponseBody
	Object updateHeader(HttpServletRequest request) {
		String filename = null;
		String loadpath = request.getSession().getServletContext()
				.getRealPath("/")
				+ "header"; // 上传文件存放目录
		System.out.println("loadpath=" + loadpath);
		DiskFileUpload fu = new DiskFileUpload();
		fu.setSizeMax(1 * 1024 * 1024); // 设置允许用户上传文件大小,单位:字节
		fu.setSizeThreshold(4096); // 设置最多只允许在内存中存储的数据,单位:字节

		// 开始读取上传信息
		int index = 0;
		List fileItems = null;

		try {
			fileItems = fu.parseRequest(request);
			System.out.println("fileItems=" + fileItems);
		} catch (Exception e) {
			e.printStackTrace();
		}

		Iterator iter = fileItems.iterator(); // 依次处理每个上传的文件
		while (iter.hasNext()) {
			FileItem item = (FileItem) iter.next();// 忽略其他不是文件域的所有表单信息
			if (!item.isFormField()) {
				String name = item.getName();// 获取上传文件名,包括路径
				name = name.substring(name.lastIndexOf("\\") + 1);// 从全路径中提取文件名
				long size = item.getSize();
				if ((name == null || name.equals("")) && size == 0)
					continue;
				int point = name.indexOf(".");
				name = (new Date()).getTime()
						+ name.substring(point, name.length()) + index;
				index++;
				File fNew = new File(loadpath, name);
				filename = name;
				try {
					item.write(fNew);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			} else // 取出不是文件域的所有表单信息
			{
				String fieldvalue = item.getString();
				// 如果包含中文应写为：(转为UTF-8编码)
				// String fieldvalue = new
				// String(item.getString().getBytes(),"UTF-8");
			}

		}
		return filename;
	}

	@RequestMapping(value = "/upImg", method = RequestMethod.POST)
	public void upImg(Map<String, Object> map, MultipartFile filedata,
			HttpServletRequest request, HttpServletResponse response) {
		response.setContentType("text/html; charset=UTF-8");
		long maxSize = 0;
		maxSize = 1024 * 1024;
		String path = request.getSession().getServletContext()
				.getRealPath("/resources/fileupload");
		String fileName = filedata.getOriginalFilename();
		Calendar calendar = Calendar.getInstance();
		long newFileName = calendar.getTimeInMillis();
		File targetFile = new File(path, newFileName + "");
		if (!targetFile.exists()) {
			targetFile.mkdirs();
		}
		// 保存
		try {
			filedata.transferTo(targetFile);
			PrintWriter out = response.getWriter();
			String pathName = request.getContextPath() + "/resources/fileupload/"
					+ newFileName;
			System.out.println(pathName);
			out.println("{\"err\":\"\",\"msg\":\"" + pathName + "\"}");// 这里返回你图片上传路径，返回json到编辑器中，这样编辑器就能及时显示图片内容了
			out.flush();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}